---
title: ''
output: pdf_document
geometry: "top=1in, bottom=1in, left=1in, right=1in"
header-includes:
- \usepackage{caption}
- \usepackage{lscape}
---

\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}

\captionsetup[table]{labelformat=empty}


```{r setup, include=FALSE, message=FALSE}

# Package setup
if (!require("pacman")) install.packages("pacman", repos = "http://cran.us.r-project.org"); library(pacman);
pacman::p_load(yaml, arrow, readr, tidyr, glue, argparse, here, purrr, stringr, dplyr, knitr, kableExtra);

# Working directory and command line argument setup
current_script = "generate_tables_and_figures/gen_covid_outputs/src/gen_covid_outputs.Rmd"
here::i_am(current_script)
source(here("R", "project_functions.R"))
task_dir = here(dirname(dirname(file.path(current_script))))
knitr::opts_knit$set(root.dir = task_dir)
cl_args <- parse_make_args(c(
  "RMD_FILE",
  "COVID_STATS_FILE",
  "OUTCOME_LABELS_FILE",
  "CONFIG_FILE",
  "OUT_DIR"
), inter_active = TRUE, task_dir = task_dir)

knitr_setup()

source('../R/table_functions.R')

```


```{r}

covid_stats <- read_csv(cl_args$COVID_STATS_FILE, show_col_types = F)

ylabels <- read_csv(cl_args$OUTCOME_LABELS_FILE, show_col_types = F) %>%
  rename(outcome = value)

params <- read_yaml(cl_args$CONFIG_FILE)

```


```{r}

get_covid_table_row <- function(yvar, covid_stats, params) {

  relevant_covid_stats <- covid_stats %>%
    filter(outcome == yvar & window == params$window)

  estimates <- relevant_covid_stats %>%
    select(outcome, term, pval_itt, beta_itt, stderr_itt) %>%
    pivot_wider(names_from = term, values_from = c(beta_itt, stderr_itt, pval_itt))

  df_means <- relevant_covid_stats %>%
    select(outcome, term, control_mean, treatment_mean) %>%
    pivot_wider(names_from = term, values_from = c(control_mean, treatment_mean)) %>%
    mutate(across(matches("mean"), ~ fmt(.x, decimals = 4)))

  df_beta <- estimates %>%
    select(-matches("stderr")) %>%
    mutate(across(matches("pval"), ~ fmt(.x))) %>%
    mutate(across(matches("beta"), ~ fmt(.x, decimals = 4))) %>%
    mutate(row_type = 'beta')

  df_se <- estimates %>%
    select(outcome, matches("stderr")) %>%
    mutate(across(matches("stderr"), ~ fmt(.x, decimals = 4, parens = TRUE))) %>%
    rename_at(vars(matches("stderr")), ~ gsub("stderr", "beta", .)) %>%
    mutate(row_type = 'stderr')

  covid_df = bind_rows(
    left_join(
      df_means,
      df_beta,
      by = 'outcome'
    ),
    df_se
  ) %>% select(row_type, outcome, everything())

  return(covid_df)
}

covid_df <- map_dfr(params$outcomes,
                    get_covid_table_row,
                    covid_stats,
                    params)

covid_df <- covid_df %>%
  select(row_type, outcome,
         control_mean_treatment_pre_covid, control_mean_treatment_post_covid, control_mean_diff,
         beta_itt_treatment_pre_covid, beta_itt_treatment_post_covid, beta_itt_diff,
         pval_itt_treatment_pre_covid, pval_itt_treatment_post_covid, pval_itt_diff) %>%
  left_join(ylabels %>% select(outcome, label), by = 'outcome') %>%
  mutate(outcome = case_when(is.na(control_mean_diff) ~ "",
                             T ~ label)) %>%
  select(-label)

```

\blandscape

```{r}

covid_table <- covid_df %>%
  select(-row_type, -control_mean_diff, -matches("treatment_mean")) %>%
  kable(booktabs=T, longtable=T, linesep = "",
        col.names = c("", "Pre-COVID", "Post-COVID", rep(c("Treatment Pre-COVID", "Treatment Post-COVID", "Difference"), 2)),
        align=c("l", rep("c", 8))) %>%
  kable_styling(font_size = 10.5) %>%
  row_spec(0, font_size = 9.5) %>%
  column_spec(1, width="18em", latex_valign = 'm') %>%
  column_spec(2:9, width="4.5em", latex_valign = 'm') %>%
  column_spec(c(3,5,8), width="4.8em", latex_valign = 'm') %>%
  column_spec(c(6,9), width="3.3em", latex_valign = 'm') %>%
  group_rows("Primary Outcome Components, Counts", 1, 6) %>%
  group_rows("All Events, Counts", 7, 10) %>%
  add_indent(c(1:10)) %>%
  add_header_above(c(" " = 1, "CM" = 2, "ITT" = 3, "P-values" = 3))

timestamp <- get_timestamp()
writeLines(covid_table, glue(cl_args$OUT_DIR, "/covid_models_with_means_up_to_date.tex"))
writeLines(covid_table, glue(cl_args$OUT_DIR, "/covid_models_with_means_{timestamp}.tex"))

covid_table

```
\elandscape